<!--
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-11-17 15:42:32
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-04-28 14:20:01
 * @FilePath: \cxl-driving-training\src\components\form\tag.vue
-->
<template>
    <div class="tag-container">
        <el-tag
            v-for="tag in data"
            :key="tag"
            class="mx-1"
            :closable="!disabled"
            size="large"
            :disable-transitions="false"
            @close="handleClose(tag)"
        >
            {{ tag }}
        </el-tag>
        <el-input
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            style="width: 200px"
            clearable
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
        />
        <template v-else>
            <el-button v-if="data.length < 6 && !disabled" class="button-new-tag ml-1" @click="showInput">
                + 标签
            </el-button>
        </template>
    </div>
</template>
<script setup lang="ts">
import { ref, nextTick, reactive, watchEffect } from 'vue'
import { ElInput } from 'element-plus'

const inputValue = ref('')
const dynamicTags = reactive<string[]>([])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const props = defineProps(['data', 'disabled'])
const emits = defineEmits(['delete', 'add'])

watchEffect(() => {
    if (props.data) {
        dynamicTags.length = 0
        dynamicTags.push(...props.data)
    }
})

const handleClose = (tag: string) => {
    emits('delete', tag)
}

const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
        if (InputRef.value!) {
            InputRef.value.input!.focus()
        }
    })
}

const handleInputConfirm = () => {
    if (inputValue.value) {
        emits('add', inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
}
</script>
<style scoped lang="scss">
.ml-1 {
    width: 80px;
}
.mx-1 {
    margin-right: 10px;
    margin-bottom: 5px;
}
</style>
